<template>
    <el-row class="home" :gutter="20" style="padding-top: 20px">
        <el-card>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
                <!--题目基本信息-->
                <h4>基本信息</h4>
                <div class="flex-box">
                    <el-form-item label="难度">

                        <span style="margin-right: 8px; font-size: 25px; font-weight: bold; color: red">*</span>

                        <el-select v-model="form.difficult" placeholder="请选择题目难度">
                            <el-option label="简单" value="1"></el-option>
                            <el-option label="中等" value="2"></el-option>
                            <el-option label="困难" value="3"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="类型">

                        <span style="margin-right: 8px; font-size: 25px; font-weight: bold; color: red">*</span>

                        <el-select v-model="form.typeId" placeholder="请选择题目类型">
                            <el-option label="选择题" value="1"></el-option>
                            <el-option label="填空题" value="2"></el-option>
                            <el-option label="编程题" value="3"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="题目集">

                        <span style="margin-right: 8px; font-size: 25px; font-weight: bold; color: red">*</span>

                        <el-select v-model="form.qcollectionId" placeholder="请选择题目集">
                            <el-option v-for="i in collectionList" :label="i.name" :value="i.id"></el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <el-form-item label="标题">
                    <el-input placeholder="请输入题目标题" v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="分数">
                    <el-input v-model="form.score" placeholder="请输入题目分数"></el-input>
                </el-form-item>
                <el-form-item label="知识点">
                    <el-tag
                            :key="tag"
                            v-for="tag in knowledgeList"
                            closable
                            :disable-transitions="false"
                            @close="handleClose(tag)"
                            type="success">
                        {{tag}}
                    </el-tag>
                    <el-input
                            class="input-new-tag"
                            v-if="inputVisible"
                            v-model="inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm"
                            @blur="handleInputConfirm">
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
                </el-form-item>
                <el-divider></el-divider>


                <!--题目描述-->
                <h4>题目描述</h4>
                <el-form-item>
                    <MdEditor ref="description"></MdEditor>
                </el-form-item>
                <el-divider></el-divider>


                <!--标准答案-->
                <h4>标准答案</h4>
                <el-form-item label="程序代码1">
                    <CodeMirror ref="codeMirror1" style="line-height: 14px"></CodeMirror>
                </el-form-item>
                <el-form-item label="程序代码2">
                    <CodeMirror ref="codeMirror2" style="line-height: 14px"></CodeMirror>
                </el-form-item>
                <el-form-item label="程序代码3">
                    <CodeMirror ref="codeMirror3" style="line-height: 14px"></CodeMirror>
                </el-form-item>

                <!--题目判定设置-->
                <h4>题目判定条件</h4>
                <el-form-item label="时间限制(单位ms)">
                    <el-input placeholder="请输入时间限制" v-model="form.timeLimit"></el-input>
                </el-form-item>
                <el-form-item label="内存限制(单位MB)">
                    <el-input placeholder="请输入内存限制" v-model="form.memoryLimit"></el-input>
                </el-form-item>

                <!--提交-->
                <el-form-item>
                    <el-button type="primary" v-if="form.id != ''" @click="updateQuestion('form')">更新</el-button>
                    <el-button type="primary" v-if="form.id == ''" @click="onSubmit('form')">创建</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </el-row>
</template>

<script>
    import MdEditor from '../../../../components/MdEditor'
    import CodeMirror from '../../../../components/CodeMirror'
    //axios
    import axios from 'axios'

    export default {
        name: "InputView",
        components: {
            MdEditor,
            CodeMirror
        },
        data(){
            return {
                form: {
                    id: '',
                    num: 0,
                    title: '',
                    doNum: 0,
                    passNum: 0,
                    score: '',
                    context: '',
                    typeId: '',
                    qcollectionId: '',
                    difficult: '',
                    author: '',
                    knowledgeNode: '',
                    timeLimit: '',
                    memoryLimit: '',
                    answer1: '',
                    answer2: '',
                    answer3: ''
                },
                rules: {
                    title: [
                        { required: true, message: '请输入题目标题', trigger: 'blur' },
                        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                    ],
                    score: [
                        { required: true, message: '请输入题目分数', trigger: 'blur' },
                        //校验正整数
                    ],
                    //题目描述，不为空
                    type: [
                        { required: true, message: '请选择题目类型', trigger: 'change'}
                    ],
                    qcollection: [
                        { required: true, message: '请选择题目集', trigger: 'change'}
                    ],
                    difficult: [
                        { required: true, message: '请选择题目困难程度', trigger: 'change'}
                    ]
                },
                knowledgeList: [],
                collectionList: [],
                inputVisible: false,
                inputValue: '',
                token: '',
                beforeCollectionId: ''
            }
        },
        methods: {
            //新增题目
            onSubmit(formName){
                //发送请求
                this.$refs[formName].validate(async valid => {
                    if (valid) {
                        var list = this.knowledgeList;
                        //修改知识点标签
                        for(var i = 0; i < list.length; i++){
                            this.form.knowledgeNode = (i == 0)
                                ? this.form.knowledgeNode + list[i]
                                : this.form.knowledgeNode + '&' + list[i];
                        }
                        //题目描述
                        this.form.context = this.$refs.description.content;
                        //代码片段
                        this.form.answer1 = this.$refs.codeMirror1.code;
                        this.form.answer2 = this.$refs.codeMirror2.code;
                        this.form.answer3 = this.$refs.codeMirror3.code;

                        let params = this.form;
                        var that = this;

                        //发送请求
                        /*
                            接口: 新增题目
                            请求地址: http://localhost:8881/producer/question/add
                            请求方法: post
                            请求参数: 题目信息
                            响应内容: 响应结果
                        */
                        axios({
                            method: 'post',
                            url: 'http://localhost:8881/producer/question/add',
                            data: params,
                            headers: {
                                token: this.token
                            }
                        }).then(function (response) {
                            var res = response.data;
                            if(res.code == 200){
                                that.$message.success('新增成功！');
                                //跳转页面
                                //that.$router.push('/admin/problem/manage')
                            }else{
                                that.$message.error('新增失败！');
                            }
                        }).catch(function (error) {
                            console.log(error);
                        });
                    } else {
                        return false
                    }
                });
            },

            //更新题目
            updateQuestion(formName){
                //发送请求
                this.$refs[formName].validate(async valid => {
                    if (valid) {
                        var list = this.knowledgeList;
                        //修改知识点标签
                        for(var i = 0; i < list.length; i++){
                            this.form.knowledgeNode = (i == 0)
                                ? this.form.knowledgeNode + list[i]
                                : this.form.knowledgeNode + '&' + list[i];
                        }
                        //题目描述
                        this.form.context = this.$refs.description.content;
                        //代码片段

                        let params = this.form;
                        var that = this;

                        //困难程度
                        var diff = this.form.difficult;
                        params.difficult = (diff == '简单') ? 1 : (diff == '中等') ? 2 : 3;

                            //发送请求
                        /*
                            接口: 更新题目
                            请求地址: http://localhost:8881/producer/question/update
                            请求方法: post
                            请求参数: 题目信息
                            响应内容: 响应结果
                        */
                        axios({
                            method: 'post',
                            url: 'http://localhost:8881/producer/question/update',
                            data: params,
                            headers: {
                                token: this.token
                            }
                        }).then(function (response) {
                            var res = response.data;
                            if(res.code == 200){
                                that.$message.success('更新成功！');
                                //跳转页面
                                // that.$router.push({
                                //     path: '/admin/problem/manage',
                                //     query: {id: that.beforeCollectionId}
                                // })
                            }else{
                                that.$message.error('更新失败！');
                            }
                        }).catch(function (error) {
                            console.log(error);
                        });
                    } else {
                        return false
                    }
                });
            },

            handleClose(tag) {
                this.knowledgeList.splice(this.knowledgeList.indexOf(tag), 1);
            },

            showInput() {
                this.inputVisible = true;
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },

            handleInputConfirm() {
                let inputValue = this.inputValue;
                if (inputValue) {
                    this.knowledgeList.push(inputValue);
                }
                this.inputVisible = false;
                this.inputValue = '';
            },

            // 刷新 （如果出现编辑器样式问题，以及不能初始化赋值回显数据，可以进行刷新操作）
            refresh() {
                this.$refs.codeMirror1.refresh()
                this.$refs.codeMirror2.refresh()
                this.$refs.codeMirror3.refresh()
            },
            // 获取编辑器的值
            getValue() {
                return this.$refs.codeMirror.code
            },
            // 回显赋值
            setValue() {
                this.$refs.codeMirror.setValue('回显的值:比如 function aa() {}')
            }
        },

        created: function () {
            var question = this.$route.query.data;
            if(typeof(question) != "undefined"){
                this.form = question;
                //知识点
                this.knowledgeList = this.form.knowledgeNode.split('&');
                //TODO 题目描述
                //TODO 代码片段
            }
            let params = {};
            var that = this;
            let token = localStorage.getItem('token');
            this.token = token;

            //发送请求
            /*
                接口: 获取全部题目集
                请求地址: http://localhost:8881/producer/qcollection/select
                请求方法: post
                请求参数: 查询条件
                响应内容: 响应结果
            */
            axios({
                method: 'post',
                url: 'http://localhost:8881/producer/qcollection/select',
                data: params,
                headers: {
                    token: token
                }
            }).then(function (response) {
                var res = response.data;
                if(res.code == 200){
                    that.collectionList = res.data.collectionList;
                }else{
                    that.$message.error('数据获取失败！');
                }
            }).catch(function (error) {
                console.log(error);
            });
        }
    }
</script>

<style scoped>
    .el-tag + .el-tag {
        margin-left: 10px;
    }
    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }

    .flex-box{
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
</style>